package com.Jning.cfengtestdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author Cfeng
 * @date 2022/7/27
 */

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    //设置欢迎页面
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

    //服务器支持跨域访问
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")  //*匹配所有的IP，设置允许访问的IP
                .allowedMethods("GET","POST","DELETE","OPTIONS")  //设置允许的Http访问方式
                .allowedHeaders("*")  //所有的请求头
                .exposedHeaders("Access-Control-Allow-Headers","Access-Control-Allow-Methods","Access-Control-Allow-Origin","Access-Control-Max-Age","X-Frame-Options") //暴露，允许跨域
                .allowCredentials(false)   //不需要凭证
                .maxAge(3600);
    }

    /**
     * 可以直接在WebMVC的配置ServerEndPointExporter这个bean
     *  自动注册使用了@ServerEndPoint注解的endpoint
     *  使用了SpringBoot内置的servlet容器，需要注册，如果没有时外部的Tomcat，不需要注入
     *  Tomcat会提供
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
